'use strict'
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')

function cssLoaders(options) {
  let context = this
  let generateLoaders = function(loader, loaderOptions) {
    const loaders = [...context.cssLoader()]

    if (loader) {
      loaders.push({
        loader: loader + '-loader',
        options: Object.assign({}, loaderOptions, {
          sourceMap: options.sourceMap
        })
      })
    }

    if (options.extract) {
      return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'
      })
    } else {
      return ['vue-style-loader'].concat(loaders)
    }
  }

  let sassResources = (context.sassResources && context.sassResources.length) ? [{
    loader: 'sass-resources-loader',
    options: {
      resources: context.sassResources.map(value => {
        return path.resolve(process.cwd(), path.join(context.root, value))
      })
    }
  }] : []

  return {
    css: generateLoaders(),
    postcss: generateLoaders(),
    less: generateLoaders('less'),
    sass: generateLoaders('sass', {
      indentedSyntax: true
    }),
    scss: generateLoaders('sass').concat(sassResources),
    stylus: generateLoaders('stylus'),
    styl: generateLoaders('stylus')
  }
}

/**
 * meipian.config.js for context
 * @param  {Object} jwconf meipian runtime congfig
 * @return {Object}        webpack config object
 */
module.exports = function(jwconf) {
  return {
    externals: {
      //TODO
    },
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    },
    module: {
      rules: [{
        test: /\.vue$/,
        loader: 'vue-loader',
        options: {
          loaders: cssLoaders.apply(jwconf, [{
            sourceMap: jwconf.isMap,
            extract: jwconf.isExtract
          }]),
          cssSourceMap: jwconf.isMap,
          cacheBusting: jwconf.isMap ? false : true,
          transformToRequire: {
            video: ['src', 'poster'],
            source: 'src',
            img: 'src',
            image: 'xlink:href'
          }
        }
      }]
    },
    plugins: [
      new webpack.ProvidePlugin({
        Vue: 'vue',
        VueRouter: 'vue-router',
        _: 'lodash'
      })
    ]
  }
}